import { ref, computed } from 'vue'
import { defineStore } from 'pinia'


// 创建一个store   公共数据
export const useAddressStore = defineStore('address', () => {
  // 数据
  const addressList = ref([
    {
      id: '1',
      name: '张三',
      tel: '13000000000',
      address: '浙江省杭州市西湖区文三路 138 号东方通信大厦 7 楼 501 室',
      isDefault: true,
    },
    {
        id: '2',
        name: '李四',
        tel: '1310000000',
        address: '浙江省杭州市拱墅区莫干山路 50 号',
    },
  ])
  // 对应的id
  const chosenAddressId = ref('');
  // 在数据里查找当前地址的id是否跟当前地址的id相等
  const curAddress = computed(() => {
    return addressList.value.find(item => item.id === chosenAddressId.value)
  })

  // 新增地址
  const addAddress = (info) => {
    // 如果默认存在  就把所有的默认地址设置为false
    if(info.isDefault){
      addressList.value.forEach(item => 
        item.isDefault = false
      )
    }
    // 去重  
    const norepeat = [...new Set([info.province,info.city,info.county,info.addressDetail])]

    addressList.value.unshift({
      ...info,
      id:Date.now(),
      address:norepeat.join('')
    })
  }


  // 编辑函数
  const editAddress = (info) => {
    // 找到对应的下标  然后修改
    const index = addressList.value.findIndex(item => item.id === info.id)
    const norepeat = [...new Set([info.province,info.city,info.county,info.addressDetail])]

    addressList.value.splice(index,1,{
      ...info,
      address:norepeat.join('')
    })
  }


  // 删除地址
  const delAddress = (id) => {
    // 找到对应的id  然后删除
    addressList.value = addressList.value.filter(item => item.id!== id)
  }


  // 函数的返回值
  return { addressList, chosenAddressId,curAddress,addAddress,delAddress,editAddress}
})
